package com.lsh.security;

import com.lsh.pojo.Permission;
import com.lsh.pojo.Role;
import com.lsh.pojo.User;
import com.lsh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.findByUsername(s);
        if(user != null){
            String username = user.getUsername();
            String password = user.getPassword();
            Set<Role> roles = user.getRoles();
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
            if(roles != null){
                for (Role role : roles) {
                    grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions != null){
                        for (Permission permission : permissions) {
                            grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
                        }
                    }
                }
            }
            return new org.springframework.security.core.userdetails.User(username,password,grantedAuthorityList);
        }
        //没有通过账号查找到信息，返回null 拒绝访问
        return null;
    }
}
